package com.pactera.base.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pactera.base.commons.utils.CopyUtil;
import com.pactera.base.commons.vo.PageData;
import com.pactera.base.commons.vo.RestResponse;
import com.pactera.base.example.entity.User;
import com.pactera.base.example.param.UserPageParam;
import com.pactera.base.example.param.UserParam;
import com.pactera.base.example.param.UserUpdateParam;
import com.pactera.base.example.service.UserService;
import com.pactera.base.example.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author wangrui
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {
    @Autowired
    private UserService service;

    @PostMapping("/add")
    @ApiOperation("新增")
    public RestResponse<Boolean> add(@RequestBody @Valid UserParam param){
        return RestResponse.getSuccessRtnMap("成功",service.save(CopyUtil.copy(param, new User())));
    }

    @PostMapping("/update")
    @ApiOperation("编辑")
    public RestResponse<Boolean> update(@RequestBody @Valid UserUpdateParam param){
        return RestResponse.getSuccessRtnMap("成功",service.updateById(CopyUtil.copy(param, new User())));
    }

    @GetMapping("/detail")
    @ApiOperation("详情")
    public RestResponse<User> detail(@RequestParam Long id){
        return RestResponse.getSuccessRtnMap("成功",CopyUtil.copy(service.getById(id),new UserVo()));
    }

    @PostMapping("/page")
    @ApiOperation("分页")
    public RestResponse<PageData<UserVo>> page(@RequestBody @Valid UserPageParam param){
        IPage<UserVo> page = service.findPage(param);
        return RestResponse.getSuccessPageRtnMap("成功",new PageData<>(page.getTotal(), page.getPages(), page.getRecords()));
    }

    @PostMapping("/delete")
    @ApiOperation("删除")
    public RestResponse<Boolean> delete(@RequestParam Long id){
        return RestResponse.getSuccessRtnMap("成功",service.removeById(id));
    }
}
